from django.http import HttpResponseRedirect
from django.shortcuts import render, HttpResponse

# Create your views here.
from cms.models import *
from cms.forms import *
from dms.settings import UPLOAD_DIR
import random



# 首页
def index(request):
    return render(request, "front/index.html")

# 文章列表
def article_list(request):
    articles = Article.objects.all()
    return render(request, "cms/article_list.html", {'articles': articles})

# 文章编辑
def article_edit(request, id=0):
    id=int(id)
    if id != 0:
        article = Article.objects.get(id=id)
    else:
        article = None
    if request.method == 'POST':
        form = ArticleForm(request.POST, instance=article)
        if form.is_valid():
            article = form.save()
            return HttpResponseRedirect('/cms/article_list')
        else:
            return render(request, 'cms/article_edit.html', locals())
    else:
        form = ArticleForm(instance=article)
    return render(request, 'cms/article_edit.html', locals())

# 文章删除
def article_delete(request, id=0):
    Article.objects.get(id=id).delete()
    return HttpResponseRedirect('/cms/article_list')

# 图片编辑
def banner_edit(request, id=0):
    id=int(id)
    if id != 0:
        banner = Banner.objects.get(id=id)
    else:
        banner = None
    if request.method == 'POST':
        form = BannerForm(request.POST,request.FILES, instance=banner)
        if form.is_valid():
            f=form.cleaned_data['f']
            if ".png" in f.name or ".PNG" in f.name or ".jpg" in f.name or ".JPG" in f.name:
                store_name = "banner_" + str( random.randint(1000, 9999)) + '.' + f.name.split('.')[-1]
                destination = open(UPLOAD_DIR + store_name, 'wb+')
                for chunk in f.chunks():
                    destination.write(chunk)
                destination.close()

            banner = form.save(commit=False)
            banner.file=store_name
            banner.save()
            return HttpResponseRedirect('/cms/banner_list')
        else:
            return render(request, 'cms/banner_edit.html', locals())
    else:
        form = BannerForm(instance=banner)
    return render(request, 'cms/banner_edit.html', locals())


# 图片列表
def banner_list(request):
    banners = Banner.objects.all()
    return render(request, "cms/banner_list.html", {'banners': banners})